package com.hanbang.taitaigou.ui.activity.aboutme.address;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.model.GetUserAddressList;
import com.hanbang.taitaigou.ui.activity.base.BaseActivity;
import com.hanbang.taitaigou.ui.widget.dialog.BaseDialog;
import com.hanbang.taitaigou.ui.widget.dialog.OnClickCallback;
import com.hanbang.taitaigou.utils.http.HttpCallBack;
import com.hanbang.taitaigou.utils.http.HttpRequestParams;
import com.hanbang.taitaigou.utils.http.JsonHelper;
import com.hanbang.taitaigou.utils.ui.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanxin on 2016/3/17.
 */
public class AboutMeAddressManagemenntActivity extends BaseActivity {
    /**
     * 新增地址
     **/
    private Button bt_add_address;
    /**
     * listview
     **/
    private ListView lv_aboutme_address_management;
    public static List<GetUserAddressList> list = new ArrayList<GetUserAddressList>();
    private ListViewAdapter listViewAdapter;

    //下拉刷新
    private SwipeRefreshLayout srl_swipe_ly_right;

    public static int ADDRESS_CHANG = 211;
    private String ss;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aboutme_address_management);
        initView();
        setOnClickListener();
        getUserAddressList();
        shuaxin();
    }


    /*
     * 设置点击事件
     */
    private void setOnClickListener() {
        bt_add_address.setOnClickListener(onClickListener);
        Intent intent = getIntent();
        ss = intent.getStringExtra("addressType");

        lv_aboutme_address_management.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (ss.equals("1")) {
                    Intent intent = new Intent();
                    intent.putExtra("id", list.get(position).getId());
                    intent.putExtra("name", list.get(position).getPurchname());
                    intent.putExtra("phone", list.get(position).getPurchtel());
                    intent.putExtra("sf", list.get(position).getProvince());
                    intent.putExtra("city", list.get(position).getCity());
                    intent.putExtra("quyu", list.get(position).getArea());
                    intent.putExtra("xiangAddress", list.get(position).getAddress());
                    setResult(RESULT_OK, intent);
                    finish();
                } else if (ss.equals("2")) {
                    Intent intent = new Intent(AboutMeAddressManagemenntActivity.this, AboutMeAddAddressManagementActivity.class);
                    intent.putExtra("type", 2);
                    intent.putExtra("id", list.get(position).getId());
                    intent.putExtra("name", list.get(position).getPurchname());
                    intent.putExtra("phone", list.get(position).getPurchtel());
                    intent.putExtra("sf", list.get(position).getProvince());
                    intent.putExtra("city", list.get(position).getCity());
                    intent.putExtra("quyu", list.get(position).getArea());
                    intent.putExtra("xiangAddress", list.get(position).getAddress());
//                startActivity(intent);
                    startActivityForResult(intent, 1000);
                }
            }
        });
    }

    @SuppressWarnings("unused")
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {

                //新增用户地址
                case R.id.bt_add_address:
                    Intent intent = new Intent();
                    intent.putExtra("type", 1);
                    intent.putExtra("addType", 1);
                    intent.setClass(AboutMeAddressManagemenntActivity.this, AboutMeAddAddressManagementActivity.class);
                    startActivityForResult(intent, 1000);
                    break;
                default:
                    break;
            }
        }
    };

    /*
     * 初始化view
     */
    private void initView() {
        // 设置顶部的标题
        setTop(null, 0, getString(R.string.top_address_management), null, 0);
        setBackArrows(findViewById(R.id.top_bar_left_iv));
        bt_add_address = (Button) findViewById(R.id.bt_add_address);

        srl_swipe_ly_right = (SwipeRefreshLayout) findViewById(R.id.srl_swipe_ly_right);
        lv_aboutme_address_management = (ListView) findViewById(R.id.lv_aboutme_address_management);
        listViewAdapter = new ListViewAdapter();
        lv_aboutme_address_management.setAdapter(listViewAdapter);

    }

    /**
     * 下拉刷新
     */

    private void shuaxin() {
        srl_swipe_ly_right.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getUserAddressList();
            }
        });
    }

    /*
     * 获取用户的地址列表
     */
    private void getUserAddressList() {
        HttpRequestParams httpRequestParams = new HttpRequestParams("GetUserAddressList");
        httpRequestParams.addUserId(userData);
        httpManager.post(httpRequestParams, new HttpCallBack<String>(this, "正在加载...") {

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray js = jsonObject.getJSONArray("result");
                    list.clear();
                    list.addAll(JsonHelper.parseCollection(js, ArrayList.class, GetUserAddressList.class));
                    listViewAdapter.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.setSwipeRefreshLayout(srl_swipe_ly_right));
    }

    /**
     * 添加了数据返回这个页面刷新下
     */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000 && resultCode == 1001) {
            getUserAddressList();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub

        super.onResume();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    class ListViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // 常见的优化ViewHolder
            final ViewHolder viewHolder;
            if (null == convertView) {
                viewHolder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.item_aboutme_address_management, null);
                viewHolder.tv_address_moren = (TextView) convertView.findViewById(R.id.tx_default);
                viewHolder.tv_address_name = (TextView) convertView.findViewById(R.id.name);
                viewHolder.tv_address_tel = (TextView) convertView.findViewById(R.id.phone);
                viewHolder.tv_address_address = (TextView) convertView.findViewById(R.id.address);
                viewHolder.iv_address_delete = (ImageView) convertView.findViewById(R.id.delete);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }


            /**
             设置用户默认地址
             */
            if (list.get(position).getIs_default() == 0 || list.size() == 1) {
                viewHolder.tv_address_moren.setText("[默认]");
                viewHolder.tv_address_moren.setTextColor(AboutMeAddressManagemenntActivity.this.getResources().getColor(R.color.main_color));
                viewHolder.tv_address_moren.setOnClickListener(null);
            } else {
                viewHolder.tv_address_moren.setText("设为 \n 默认");
                viewHolder.tv_address_moren.setTextColor(AboutMeAddressManagemenntActivity.this.getResources().getColor(R.color.black));
                viewHolder.tv_address_moren.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if ((AboutMeAddressManagemenntActivity.this).isLogin(true)) {
                            final HttpRequestParams params = new HttpRequestParams("SetDefaultAddress");
                            params.addUserId(userData);
                            params.addBodyParameter("id", String.valueOf(list.get(position).getId()));
                            x.http().post(params, new HttpCallBack<String>(AboutMeAddressManagemenntActivity.this, AboutMeAddressManagemenntActivity.this.getString(R.string.loadding), false) {
                                @Override
                                public void onSuccess(String result) {
                                    super.onSuccess(result);
                                    //"result":1,"msg":"设置成功"
                                    try {
                                        JSONObject jsonObject = new JSONObject(result);
                                        ToastUtils.showShort(AboutMeAddressManagemenntActivity.this, jsonObject.getString("msg"));
                                        if (jsonObject.getInt("status") == 1) {
                                            for (GetUserAddressList d : list) {
                                                d.setIs_default(1);
                                            }
                                            list.get(position).setIs_default(0);
                                            listViewAdapter.notifyDataSetChanged();
                                            Intent intent = new Intent();
                                            intent.setAction("upAddress");
                                            sendBroadcast(intent);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                    }
                });

            }

            /**
             * 删除用户地址
             */
            viewHolder.iv_address_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BaseDialog dialog = new BaseDialog(AboutMeAddressManagemenntActivity.this, BaseDialog.MODE.CONFIRM);
                    dialog.setTitleMain("提示");
                    dialog.setMainColor(getResources().getColor(R.color.red));
                    dialog.setContent("是否确认删除？");
                    dialog.setOnClickCallback(new OnClickCallback() {
                        @Override
                        public void onClick(BaseDialog dialog, Object number, Object content) {
                            if ((Integer) number == 2) {
                                if ((AboutMeAddressManagemenntActivity.this).isLogin(true)) {
                                    final HttpRequestParams params = new HttpRequestParams("DelUserAddress");
                                    params.addUserId(userData);
                                    params.addBodyParameter("id", String.valueOf(list.get(position).getId()));
                                    x.http().post(params, new HttpCallBack<String>(AboutMeAddressManagemenntActivity.this, AboutMeAddressManagemenntActivity.this.getString(R.string.loadding), false) {
                                        @Override
                                        public void onSuccess(String result) {
                                            super.onSuccess(result);

                                            try {
                                                JSONObject jsonObject = new JSONObject(result);
                                                ToastUtils.showShort(AboutMeAddressManagemenntActivity.this, jsonObject.getString("msg"));
                                                if (jsonObject.getInt("status") == 1) {
                                                    Intent intent = new Intent(AboutMeAddAddressManagementActivity.ADDRESS_CHANG);
                                                    intent.putExtra("type", 1);
                                                    AboutMeAddressManagemenntActivity.this.sendBroadcast(intent);
                                                    list.remove(position);
                                                    listViewAdapter.notifyDataSetChanged();
                                                }
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    });
                    dialog.show();
                }
            });
            viewHolder.tv_address_name.setText(list.get(position).getPurchname());
            viewHolder.tv_address_tel.setText(list.get(position).getPurchtel());
            viewHolder.tv_address_address.setText(list.get(position).getProvince()
                    + list.get(position).getCity()
                    + list.get(position).getArea()
                    + list.get(position).getAddress());
            return convertView;
        }

        class ViewHolder {
            private TextView tv_address_moren;
            private TextView tv_address_name;
            private TextView tv_address_tel;
            private TextView tv_address_address;
            private ImageView iv_address_delete;
        }
    }

}
